package com.chat.controller;

import com.chat.entry.vo.user.UploadImageVO;
import com.chat.properties.AliyunOSSProperties;
import com.chat.result.Result;
import com.chat.utils.AliyunOSSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.security.Principal;

@Slf4j
@Api(tags = "上传文件")
@RestController
@RequestMapping("/api/upload")
public class UploadController {
    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;

    @ApiOperation(value = "上传图片", notes = "上传图片成功")
    @PostMapping("/image")
    public Result uploadImage(
            @ApiParam(value = "图片", required = true) MultipartFile file,
            Principal principal) throws Exception {
        // 获取原始文件名，截取后缀
        String originalFilename = file.getOriginalFilename();
        log.info("原始文件名：{}", originalFilename);

        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 调用阿里云OSS工具类，讲文件上传到OSS
        String url = AliyunOSSUtil.upload(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getBucketName(), aliyunOSSProperties.getRegion(), file.getBytes(), extName);

        UploadImageVO uploadImageVO = new UploadImageVO(url);
        return Result.success("上传成功", uploadImageVO);
    }
}
